import { api } from './client';
import { Course, Student, Teacher } from '../types';
import { mockStudent, mockCourses, mockMyCourses, mockSelectCourse, mockDropCourse } from './mockData';

// 辅助函数：尝试调用真实API，失败则使用mock
async function tryApiOrMock<T>(
  apiCall: () => Promise<T>,
  mockCall: () => T | Promise<T>
): Promise<T> {
  try {
    return await apiCall();
  } catch (e: any) {
    if (e.isMock || e.message === 'USE_MOCK_DATA') {
      return await mockCall();
    }
    throw e;
  }
}

export const loginStudent = (username: string, password: string) => {
  return api<{ token: string; user: Student }>('/auth/login', {
    method: 'POST',
    body: JSON.stringify({ username, password, role: 'student' }),
  }).catch((error: any) => {
    if (error.isMock || error.message === 'USE_MOCK_DATA') {
      throw new Error('后端服务不可用，请检查后端是否正在运行');
    }
    throw error;
  });
};

export const getMe = () =>
  tryApiOrMock(
    () => api<Student>('/students/me'),
    () => Promise.resolve(mockStudent)
  );

export const getApprovedCourses = () =>
  tryApiOrMock(
    () => api<Course[]>('/courses?approved=true'),
    () => Promise.resolve(mockCourses)
  );

export const getMyCourses = () =>
  tryApiOrMock(
    () => api<Course[]>('/students/me/courses'),
    () => Promise.resolve([...mockMyCourses])
  );

export const selectCourse = (courseId: string) =>
  tryApiOrMock(
    () => api<void>('/students/me/courses', {
      method: 'POST',
      body: JSON.stringify({ courseId }),
    }),
    () => mockSelectCourse(courseId)
  );

export const dropCourse = (courseId: string) =>
  tryApiOrMock(
    () => api<void>(`/students/me/courses/${courseId}`, { method: 'DELETE' }),
    () => mockDropCourse(courseId)
  );

export const updateProfile = (data: Partial<Student>) =>
  tryApiOrMock(
    () => api<Student>('/students/me', {
      method: 'PATCH',
      body: JSON.stringify(data),
    }),
    () => {
      // Mock更新：更新mockStudent对象
      Object.assign(mockStudent, data);
      return Promise.resolve({ ...mockStudent });
    }
  );

export const changePassword = (data: { oldPassword: string; newPassword: string }) =>
  tryApiOrMock(
    () => api<{ success: boolean }>('/auth/me/password', {
      method: 'PATCH',
      body: JSON.stringify(data),
    }),
    () => {
      return Promise.resolve({ success: true });
    }
  );

// 根据教师名称获取教师信息
export const getTeacherByName = (teacherName: string) =>
  tryApiOrMock(
    () => api<Teacher>(`/students/teachers/${encodeURIComponent(teacherName)}`),
    async () => {
      // Mock: 从mockTeachers中查找匹配的教师
      const { mockTeachers } = await import('./mockData');
      const teacher = mockTeachers.find(t => t.name === teacherName);
      if (teacher) {
        return Promise.resolve({ ...teacher });
      }
      // 如果找不到，返回一个默认的教师信息
      return Promise.resolve({
        id: `teacher-${teacherName}`,
        name: teacherName,
        college: '未知学院',
        account: 'unknown',
        title: '教师',
      } as Teacher);
    }
  );


